<template>
  <Dialog v-model="dialogVisible" title="工作流统计" width="1000px">
    <div v-loading="loading">
      <el-form :model="queryForm" :inline="true" class="query-form">
        <el-form-item label="统计周期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="loadStatistics"
          />
        </el-form-item>
        
        <el-form-item label="统计维度">
          <el-select v-model="queryForm.dimension" @change="loadStatistics">
            <el-option label="按状态统计" value="status" />
            <el-option label="按职业统计" value="profession" />
            <el-option label="按处理人统计" value="handler" />
            <el-option label="按时间统计" value="time" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card title="总体概况" class="statistics-card">
            <div class="overview-stats">
              <div class="stat-item">
                <div class="stat-value">{{ overviewData.total }}</div>
                <div class="stat-label">总申请数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ overviewData.pending }}</div>
                <div class="stat-label">待处理</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ overviewData.processing }}</div>
                <div class="stat-label">处理中</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ overviewData.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card title="处理效率" class="statistics-card">
            <div class="efficiency-stats">
              <div class="efficiency-item">
                <span class="label">平均处理时间：</span>
                <span class="value">{{ efficiencyData.avgProcessTime }} 小时</span>
              </div>
              <div class="efficiency-item">
                <span class="label">最快处理时间：</span>
                <span class="value">{{ efficiencyData.minProcessTime }} 小时</span>
              </div>
              <div class="efficiency-item">
                <span class="label">最慢处理时间：</span>
                <span class="value">{{ efficiencyData.maxProcessTime }} 小时</span>
              </div>
              <div class="efficiency-item">
                <span class="label">超时处理数：</span>
                <span class="value">{{ efficiencyData.overtimeCount }} 件</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card title="详细统计" class="statistics-card">
            <el-table :data="detailStatistics" border>
              <el-table-column 
                :prop="getColumnProp()" 
                :label="getColumnLabel()" 
                width="200" 
              />
              <el-table-column prop="count" label="数量" width="100" />
              <el-table-column prop="percentage" label="占比" width="100">
                <template #default="{ row }">
                  {{ row.percentage }}%
                </template>
              </el-table-column>
              <el-table-column prop="avgTime" label="平均处理时间" width="150">
                <template #default="{ row }">
                  {{ row.avgTime }} 小时
                </template>
              </el-table-column>
              <el-table-column label="趋势" width="100">
                <template #default="{ row }">
                  <el-tag :type="getTrendType(row.trend)">
                    {{ getTrendText(row.trend) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="remarks" label="备注" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card title="状态分布" class="statistics-card">
            <div ref="statusChartRef" style="height: 300px;"></div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card title="处理趋势" class="statistics-card">
            <div ref="trendChartRef" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <template #footer>
      <el-button @click="exportStatistics" type="primary">导出统计报告</el-button>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'WorkflowStatistics' })

const dialogVisible = ref(false)
const loading = ref(false)
const statusChartRef = ref()
const trendChartRef = ref()

const queryForm = reactive({
  dateRange: null,
  dimension: 'status'
})

const overviewData = reactive({
  total: 0,
  pending: 0,
  processing: 0,
  completed: 0
})

const efficiencyData = reactive({
  avgProcessTime: 0,
  minProcessTime: 0,
  maxProcessTime: 0,
  overtimeCount: 0
})

const detailStatistics = ref([])

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  
  // 设置默认时间范围（最近30天）
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  queryForm.dateRange = [startDate, endDate]
  
  await loadStatistics()
}

/** 加载统计数据 */
const loadStatistics = async () => {
  try {
    loading.value = true
    
    // TODO: 调用获取工作流统计的API
    // const data = await getWorkflowStatistics(queryForm)
    
    // 模拟数据
    overviewData.total = 156
    overviewData.pending = 23
    overviewData.processing = 45
    overviewData.completed = 88
    
    efficiencyData.avgProcessTime = 24.5
    efficiencyData.minProcessTime = 2.3
    efficiencyData.maxProcessTime = 72.8
    efficiencyData.overtimeCount = 8
    
    detailStatistics.value = [
      {
        name: '待审核',
        count: 23,
        percentage: 14.7,
        avgTime: 0,
        trend: 'up',
        remarks: '较上周增加3件'
      },
      {
        name: '审核中',
        count: 45,
        percentage: 28.8,
        avgTime: 18.5,
        trend: 'stable',
        remarks: '处理正常'
      },
      {
        name: '已通过',
        count: 78,
        percentage: 50.0,
        avgTime: 22.3,
        trend: 'up',
        remarks: '通过率较高'
      },
      {
        name: '已拒绝',
        count: 10,
        percentage: 6.4,
        avgTime: 15.2,
        trend: 'down',
        remarks: '拒绝率下降'
      }
    ]
    
    await nextTick()
    renderCharts()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

/** 获取列属性 */
const getColumnProp = () => {
  const propMap = {
    status: 'name',
    profession: 'professionName',
    handler: 'handlerName',
    time: 'timeRange'
  }
  return propMap[queryForm.dimension] || 'name'
}

/** 获取列标签 */
const getColumnLabel = () => {
  const labelMap = {
    status: '状态',
    profession: '职业',
    handler: '处理人',
    time: '时间段'
  }
  return labelMap[queryForm.dimension] || '分类'
}

/** 获取趋势类型 */
const getTrendType = (trend: string) => {
  const typeMap = {
    up: 'danger',
    down: 'success',
    stable: 'info'
  }
  return typeMap[trend] || 'info'
}

/** 获取趋势文本 */
const getTrendText = (trend: string) => {
  const textMap = {
    up: '上升',
    down: '下降',
    stable: '稳定'
  }
  return textMap[trend] || '稳定'
}

/** 渲染图表 */
const renderCharts = () => {
  // TODO: 使用ECharts渲染图表
  // 这里需要引入ECharts库并实现图表渲染
  console.log('渲染图表')
}

/** 导出统计报告 */
const exportStatistics = () => {
  try {
    // TODO: 调用导出统计报告的API
    ElMessage.success('统计报告导出成功')
  } catch (error) {
    console.error('导出统计报告失败:', error)
    ElMessage.error('导出统计报告失败')
  }
}

defineExpose({ open })
</script>

<style scoped>
.query-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.statistics-card {
  margin-bottom: 20px;
}

.overview-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.stat-item {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.efficiency-stats {
  padding: 10px 0;
}

.efficiency-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.efficiency-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.efficiency-item .label {
  color: #606266;
}

.efficiency-item .value {
  font-weight: bold;
  color: #303133;
}
</style>
